import { createRouter, createWebHistory } from 'vue-router'
import { constantRouterMap,errorRouter } from './modules/staticRouter'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import userStore from "@/stores/modules/user"
import permissionStore from "@/stores/modules/permission"
import { initDynamicRouter } from "./modules/dynamicRouter";
import { LOGIN_PATH } from '@/stores/mutation-types'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...constantRouterMap,...errorRouter],
  strict: false,
	scrollBehavior: () => ({ left: 0, top: 0 })
})

/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async (to, from, next) => {

// 1.NProgress 开始
NProgress.start();
document.title = to.meta.title?to.meta.title + ' - 赛维尔业务中台':'赛维尔业务中台'

// 2.如果是访问登陆页，直接放行
if (to.path === LOGIN_PATH) return next();

// 3.判断是否有 Token，没有重定向到 login
const user = userStore();
if (!user.token) return next({ path: LOGIN_PATH, replace: true });

// 4.如果没有菜单列表，就重新请求菜单列表并添加动态路由
const pre = permissionStore()
if (!pre.authMenuListGet.length) {
  await initDynamicRouter();
  return next({ ...to, replace: true });
}

// 5.正常访问页面
next();
})

/**
 * @description 路由跳转结束
 * */
router.afterEach(() => {
	NProgress.done();
});

/**
 * @description 路由跳转错误
 * */
router.onError(error => {
	NProgress.done();
	// ElNotification.error({ title: "路由错误", message: error.message });
});

export default router
